package com.leslie.hhcommunity.controller;

import com.leslie.hhcommunity.entity.Event;
import com.leslie.hhcommunity.entity.User;
import com.leslie.hhcommunity.event.EventProducer;
import com.leslie.hhcommunity.service.LikeService;
import com.leslie.hhcommunity.util.CommunityConstant;
import com.leslie.hhcommunity.util.CommunityUtil;
import com.leslie.hhcommunity.util.HostHolder;
import com.leslie.hhcommunity.util.RedisKeyUtil;
import io.netty.util.internal.UnstableApi;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

/**
 * @author
 * @PackageName:com.leslie.hhcommunity.controller
 * @ClassnName:LikeController
 * @Description:
 * @Date 2022/1/5  18:20
 */
@Controller
public class LikeController implements CommunityConstant {

	@Autowired
	LikeService likeService;
	@Autowired
	HostHolder hostHolder;
	@Autowired
	private EventProducer eventProducer;
	@Autowired
	private RedisTemplate redisTemplate;

	/**
	 * 点赞
	 *
	 * @param entityType
	 * @param entityId
	 * @return
	 */
	@RequestMapping(value = "/like", method = RequestMethod.POST)
	@ResponseBody
	public String like(int entityType, int entityId, int entityUserId, int postId) {
		User user = hostHolder.getUser();

		//点赞
		likeService.like(user.getId(), entityType, entityId, entityUserId);
		//数量
		long likeCount = likeService.findEntityLikeCount(entityType, entityId);
		//状态
		int likeStatus = likeService.findEntityLikeStatus(user.getId(), entityType, entityId);
		//返回结果
		Map<String, Object> map = new HashMap<>();
		map.put("likeCount", likeCount);
		map.put("likeStatus", likeStatus);

		// 触发事件
		if (likeStatus == 1) {
			Event event = new Event()
					.setTopic(TOPIC_LIKE)
					.setUserId(user.getId())
					.setEntityType(entityType)
					.setEntityId(entityId)
					.setEntityUserId(entityUserId)
					.setData("postId", postId);
			eventProducer.fireEvent(event);
		}

		// 计算帖子的分数
		if (entityType == ENTITY_TYPE_POST){
			String redisKey = RedisKeyUtil.getPostScoreKey();
			redisTemplate.opsForSet().add(redisKey, postId);
		}

		return CommunityUtil.getJSONString(0, null, map);
	}
}
